package com.hengpeng.itfints.controller.member;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.constants.SystemConfigConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.userInfo.UserInfoResponse;
import com.hengpeng.itfinbase.message.userInfo.UserLoginRequest;
import com.hengpeng.itfinbase.persist.Partner;
import com.hengpeng.itfinbase.persist.Partner.PartnerType;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfints.constants.SystemConfigUtil;
import com.hengpeng.itfints.constants.TSConstants;
import com.hengpeng.itfints.controller.BaseController;
import com.hengpeng.itfints.vo.MemberSession;
import com.hengpeng.itfints.webcache.PageCacheUtils;

@Controller
public class LoginController extends BaseController
{
	@RequestMapping(value = "/login")
	@ResponseBody
	public ServiceResult<?> login(HttpServletRequest request,HttpServletResponse res, ModelMap map, String username, String password,
			String url) throws Exception {
		if (username == null || username.trim().equals("")) {
			return validateFailure("必须输入登录帐户");
		}
		if (password == null || password.equals("")) {
			return validateFailure("必须输入登录密码");
		}
//		if (checkcode == null || checkcode.equals("")) {
//			return validateFailure("必须输入验证码");
//		}
//		String vcode = (String) request.getSession().getAttribute("vcode");
//		String wanneng = Configuration.getValue("itfints.validate.code");
//
//		boolean isValidate = false;
//		if (wanneng == null) {
//			isValidate = checkcode.equals(vcode);
//		} else {
//			isValidate = checkcode.equals(vcode) || wanneng.equals(checkcode);
//		}
//		if (!isValidate) {
//			return validateFailure("验证码错误");
//		}

		UserLoginRequest userLoginRequest = new UserLoginRequest();
		userLoginRequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_LOGIN);
		userLoginRequest.setUsername(username);
		userLoginRequest.setPassword(password);
		userLoginRequest.setUserIpAddress(request.getRemoteAddr());
		UserInfoResponse response = (UserInfoResponse) serviceFactory.getProtFactory().remoteTrans(userLoginRequest);
		ServiceResult<UserInfo> sr = getServiceResult(response, UserInfo.class);
		sr.setReturnValue(response.getUserInfo());
		if (!sr.getIsSuccess()) {
			return sr;
		}
		MemberSession member = serviceFactory.getUserService().refreshSessionUser(response.getUserInfo().getUserName());
		request.getSession().setAttribute(TSConstants.CLIENT_SESSION_MEMBER, member);
		Partner partner = serviceFactory.getPersistService().get(Partner.class,SystemConfigUtil.getConfigValue(SystemConfigConstants.PARTNER_ID));
		if (partner != null && !partner.getPartnerType().equals(PartnerType.FUND)) {
			member.setIsTrust(true);
		}
		if (url != null && !url.trim().equals("")) {
			try {
				sr.setMessage(java.net.URLDecoder.decode(url, "utf-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		} else {
			sr.setMessage(null);
		}
		/**
		 * 读取cookie中登陆后前往的地址
		 */
		String backurl = "";
		Cookie[] cookies = request.getCookies();
		for (Cookie c : cookies) {
			if ("backurl".equals(c.getName())) {
				backurl = c.getValue();
				break;
			}
		}
		if (!StringHelper.isEmpty(backurl)) {
			sr.setMessage(backurl);
		}
		/**
		 * 删除返回地址
		 */
		Cookie cookie = new Cookie("backurl",backurl);
		cookie.setMaxAge(0);
		res.addCookie(cookie);
		return sr;
	}

	@RequestMapping(value = "/loginRedirect")
	public String login(HttpServletRequest request, ModelMap map, String uname, String password)
	{
		if (validateObjectsNull(uname))
		{
			return returnErrorPage(map);
		}
		if (uname.indexOf("@") != -1)
		{
			uname = null;
		}
		else if (uname.matches("^\\d+$"))
		{
			uname = null;
		}
		UserLoginRequest userLoginRequest = new UserLoginRequest();
		userLoginRequest.setTransType(TransCodeConstants.MemberTransCode.MEMBER_LOGIN);
		userLoginRequest.setUsername(uname);
		userLoginRequest.setPassword(password);
		userLoginRequest.setUserIpAddress(request.getRemoteAddr());
		UserInfoResponse response = (UserInfoResponse) serviceFactory.getProtFactory().remoteTrans(userLoginRequest);
		ServiceResult<UserInfo> sr = getServiceResult(response, UserInfo.class);
		sr.setReturnValue(response.getUserInfo());
		if (sr.getIsSuccess())
		{
			MemberSession member = serviceFactory.getUserService().refreshSessionUser(
					response.getUserInfo().getUserName());
			request.getSession().setAttribute(TSConstants.CLIENT_SESSION_MEMBER, member);
			return "/index.jsp";
		}
		else
		{
			return returnErrorPage(map, sr.getMessage());
		}
	}

	@RequestMapping(value = "/loginout")
	public String loginout(HttpServletRequest request, HttpServletResponse response, ModelMap map)
	{
		MemberSession session = getSessionMember(request);
		if (session != null)
		{
			session.setIsLogin(false);
			UserInfo user = serviceFactory.getUserService().getUserByUserName(session.getUser().getUserName());
			map.put("endTime", new Date());
			map.put("loginTime", user.getLastLoginTime());
			PageCacheUtils.getInstance().remove("indexCacheFilter", "/itfints/index.htm");//清除index.jsp
		}
		request.getSession().removeAttribute(TSConstants.CLIENT_SESSION_MEMBER);
		return "redirect:/index.htm";
	}

	@RequestMapping(value = "/refresh")
	public String refresh(HttpServletRequest request)
	{
		refreshSessionMember(request);
		return "redirect:/";
	}

	@RequestMapping(value = "/refreshByAjax")
	@ResponseBody
	public ServiceResult<?> refreshByAjax(HttpServletRequest request)
	{
		ServiceResult<?> result = new ServiceResult<String>();
		result.setIsSuccess(false);
		MemberSession session = getSessionMember(request);
		if (session != null && session.getUser() != null)
		{
			MemberSession new_session = serviceFactory.getUserService().refreshSessionUser(
					session.getUser().getUserName());
			request.getSession().setAttribute(TSConstants.CLIENT_SESSION_MEMBER, new_session);
			result.setIsSuccess(true);
		}
		return result;
	}
	
	@RequestMapping(value = "/checkLogin")
    @ResponseBody
    public ServiceResult<String> checkLogin(HttpServletRequest request)
    {
        ServiceResult<String> result = new ServiceResult<String>();
        result.setIsSuccess(false);
        MemberSession session = getSessionMember(request);
        if (session != null && session.getUser() != null)
        {
            MemberSession new_session = serviceFactory.getUserService().refreshSessionUser(
                    session.getUser().getUserName());
            request.getSession().setAttribute(TSConstants.CLIENT_SESSION_MEMBER, new_session);
            result.setIsSuccess(true);
            result.setReturnValue(new_session.getUser().getUserName());
        }
        return result;
    }
}
